import { Component, OnInit , ElementRef, ViewChild, AfterViewInit} from '@angular/core';
import { FetchService } from '../../../core/net/fetch.service';
import { differenceInCalendarDays } from 'date-fns';
import * as _ from 'lodash';
import { UtilService } from '../../../core/util/util.service';
import * as moment from 'moment';
import { Router } from '@angular/router';
import { DispatchPlanService } from '../dispatch-plan.service';

@Component({
    selector: 'app-slb-dispatch-plan',
    templateUrl: './slb-dispatch-plan.component.html',
    styleUrls: ['./slb-dispatch-plan.component.scss']
})
export class SlbDispatchPlanComponent implements OnInit, AfterViewInit {
    tableData = [];
    year = "";    // 默认查后一年年
    tableHeight = "400px";
    scrollConfig =  {
        y: '400px'
    };
    pageNum = 1;
    pageSize = 10;
    total: number;
    loading = true;
    @ViewChild('wrap') elementView: ElementRef;
    constructor(
        private fetchService: FetchService,
        private util: UtilService,
        private router: Router,
        private dispatchService: DispatchPlanService,
    ) {
    }

    ngOnInit() {
        this.getGridData();
    }
    ngAfterViewInit() {
        this.scrollConfig.y = (this.elementView.nativeElement.offsetHeight - 160) + 'px';
    }
    getGridData(reset: boolean = false): void {
        if (reset) {
            this.pageNum = 1;
        }
        const params = {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            reportId: 1,
            cycle: moment(this.year).year() || "",
            orderByField: "cycle desc ",
            orderBy: ", cast(m as UNSIGNED INTEGER)  desc,data_type  desc",
        };
        this.fetchService.post<any>('plan/wrsSchedulePlan/list', params).subscribe(res => {
            this.loading = false;
            if (res) {
                this.total = res['total'];
                this.tableData = res['list'];
            } else {
                this.total = 0;
                this.tableData = [];
            }
        });
    }

    disabledDate = (current: Date): boolean => {
        // 不能选明年之后的日期
        return differenceInCalendarDays(current, moment().add(1, 'y').valueOf()) > 0;
    }

    openDetailPage(type, cycle?, name?): void {
        this.router.navigate(['/dispatch-plan/MWR-dispatch-add'], { skipLocationChange: true, queryParams: {type: type, year: cycle, name: name}});
    }

    exportFile(data): void {
        const params = {
            reportId: 1,
            y: data.cycle,
        };
        this.dispatchService.exportExcel(params, data.name);
    }

    reset(): void {
        this.year = "";
        this.getGridData(true);
    }
}
